package com.xucy.springboot.jvm.oom;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author xucy
 * @Date 2019-10-12 11:23
 * @Description 测试各种不同的内存溢出场景
 **/

public class OomTest {

    //测试字符串常量过多导致堆溢出
    public static void test1(){
        String str="hello";
        while(true){
            str=str+str;
            str.intern();
        }
    }

    static class TestObject{

    }
    //测试创建对象过多引起的堆溢出
    public static void test2(){
        List<TestObject> testObjects=new ArrayList<>();
       while (true){
           TestObject testObject=new TestObject();
           testObjects.add(testObject);
           System.out.println(testObject);
       }
    }

    //递归引发StackOverFlow
    public static void test3(){
        while (true){
            test3();
        }
    }

    //创建多线程 引发虚拟机栈 oom
    public static void test4(){
        while (true){
            Thread thread=new Thread(()-> {
                try {
                    Thread.sleep(1000000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("oom");
            });
            thread.start();
        }
    }

    //创建大量的类来模拟元空间溢出
    public static void test5(){
        while (true){
            Enhancer enhancer=new Enhancer();
            enhancer.setSuperclass(JavaMethodAreaOOM.class);
            enhancer.setUseCache(false);
            enhancer.setCallback(new MethodInterceptor() {
                @Override
                public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                    return methodProxy.invokeSuper(o,objects);
                }
            });
            enhancer.create();
        }
    }
    public static void main(String[] args) {
        String num="00";
        if(num==null || (!"0".equals(num))){

            System.out.println("111");
        }
    }
}
